/*
 * @Description:
 * @Author: zheng yiliang
 * @Date: 2021-03-11 22:11:13
 * @LastEditTime: 2021-04-11 22:47:26
 * @LastEditors: zheng yiliang
 */
import { constantRoutes } from '@/router'
// import { getRoutes } from '@/api/role'
import { routerMap } from '@/router/router-map'

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes (routes = []) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (tmp.children) {
      tmp.children = filterAsyncRoutes(tmp.children)
    }
    tmp.component = routerMap[tmp.component]
    res.push(tmp)
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
    // .sort((x, y) => {
    //   if (x.position && y.position) {
    //     return x.position - y.position
    //   }
    // })
  }
}

const actions = {
  generateRoutes ({ commit }, data) {
    return new Promise(async (resolve, reject) => {
      // let accessedRoutes
      // if (roles.includes('admin')) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // }
      // const { _RejCode, _RejMsg, data } = await getRoutes(roleId)
      // if (_RejCode !== '00000000') reject(_RejMsg)
      const accessedRoutes = filterAsyncRoutes(data)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
